package com.zhujiaji.util;

import com.alibaba.fastjson.JSONObject;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author 谢金成
 * @date 2024/3/18 16:57
 */
public class QiniuUtil {

    private static final String accessKey = "-YuXexv0waccGjWUb_5yvZdNdXfmc-vWbIezNtI1";
    private static final String secretKey = "0dyML50Ur9y07AajkbHCh2UPc_SgN8qNds81JrZY";
    private static final String bucket = "librarym";

    private static final String domain = "http://sajdkl1qz.hb-bkt.clouddn.com/";

    public static String upload(MultipartFile multipartFile) {
        Configuration cfg = new Configuration(Region.huabei());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;
        UploadManager uploadManager = new UploadManager(cfg);

        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);

        try {
            InputStream inputStream = multipartFile.getInputStream();
            Response response = uploadManager.put(inputStream, null, upToken, null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = JSONObject.parseObject(response.bodyString(), DefaultPutRet.class);
            return domain + putRet.key;
        } catch (QiniuException ex) {
            ex.printStackTrace();
            if (ex.response != null) {
                System.err.println(ex.response);
                try {
                    String body = ex.response.toString();
                    System.err.println(body);
                } catch (Exception ignored) {
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "";
    }

    public static void delete(String url) {
        Auth auth = Auth.create(accessKey, secretKey);
        Configuration cfg = new Configuration(Region.huabei());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;
        BucketManager bucketManager = new BucketManager(auth, cfg);
        String key = url.substring(url.lastIndexOf("/") + 1, url.length());
        try {
            bucketManager.delete(bucket, key);
        } catch (QiniuException e) {
            e.printStackTrace();
        }
    }
}
